package com.rectcircle.db

import com.rectcircle.config.LibraryDbSchema
import com.rectcircle.model.{Author, Book}
import org.squeryl.PrimitiveTypeMode._

object BookDb {
	
	
	import com.rectcircle.config.LibraryDbSchema._
	
	
	/**
	 *
	 * 直接插入
	 *
	 * @param a
	 * @return
	 */
	def save(a: Book) = books.insert(a)
	
	/**
	 * 更新根据主键
	 *
	 * @param a
	 */
	def updateById(a: Book) = books.update(a)
	

	
	//子查询，通过作者名查询
	def findByAuthorName(name:String) = {
		from(books)(b=>
			where(b.authorId in
		  		from (AuthorDb.findByFirstName(name))( //利用已存在查询
					a => select(a.id)
				)
			)
			select(b)
		)
	}
	
	//表连接1
	def findWithAuthorByBookName(name:String) = {
		from(books, authors)((b,a)=>
		  	where(b.title === name and b.authorId === a.id)
			select((b,a))
		)
	}
	
	
	def withAuthor(book: Book) = {
		book.author = LibraryDbSchema.authorToBooks.right(book).single
		book
	}
	
	def withReaders(book: Book) = {
		book.readers = LibraryDbSchema.borrowals.right(book).associationMap.toVector
		book
	}
	
	//分页
	def findBooksByAuthorAndPage(author: Author, offset: Int, pageLength: Int) = {
		books.where(_.authorId===author.id).page(offset,pageLength)
	}
	
	
	
}